<template>
    <div>
        <n-form
            label-align="left"
            label-placement="left"
            label-width="60px"
            style="margin-top:25px"
            @submit.native.prevent
        >
            <n-form-item label="位置">
                <n-input-number v-model:value="target.position" style="width:120px" :min="target.minPosition" :max="target.maxPosition">
                    <template #suffix>°</template>
                </n-input-number>
            </n-form-item>
            <n-form-item>
                <DebouncerSlider
                        v-model:value="target.position"
                        :min=target.minPosition
                        :max=target.maxPosition
                        :delay="20"
                        :marks="sliderMarks"
                        :format-tooltip="formatTooltip"
                        />
            </n-form-item>
            <n-form-item label="范围">
                <n-select style="width:100px" v-model:value="range" :options="rangeOptions" />
            </n-form-item>
        </n-form>

    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { AppModel } from '../../../../model/AppModel';
import { BeServo } from '../../../../model/parts/Servo';
import DebouncerSlider from '../../../common/DebouncerSlider.vue';

const props = defineProps<{
    model: AppModel ,
    target: BeServo ,
}>()

const range = ref(295)

const sliderMarks: {[key:string]:string} = reactive({
    0: '0°' ,
    90: '90°' ,
    180: '180°' ,
})
let maxPos = 0
let midPos = 0
updateMarks()

const rangeOptions = [
    {label:'0° - 270°', value: 270} ,
    {label:'0° - 295°', value: 295} ,
    {label:'0° - 360°', value: 360} ,
]


watch(()=>props.target, ()=>{
    range.value = props.target?.maxPosition
    updateMarks()
})
function onRangeChanged (value: number) {
    console.log(value, range.value)
    props.target.maxPosition = value
    updateMarks()
}
watch(range, onRangeChanged)

function updateMarks() {
    let newMax = range.value
    if( newMax!=maxPos ) {
        delete sliderMarks[maxPos]
        maxPos = newMax
        sliderMarks[newMax] = newMax + '°'
    }
    let newMid = newMax/2
    if(newMid!=midPos) {
        if(midPos!=180) {
            delete sliderMarks[midPos]
        }
        midPos = newMid
        if(midPos!=180) {
            sliderMarks[midPos] = midPos + '°'
        }
    }
}

function formatTooltip(v: number) {
    return v+'°'
}
</script>